/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
var serverPath = '//magabot-control.googlecode.com/hg/';

//Account of the application
var jid = "magabot.hangouts@gmail.com";
var password = "hangouts12345";

var robotEmail;
var lastMessage = " ";
var lastSetter = "";

var isForwardKeyDown = 0;

//Milliseconds between each frame.
var INTERVAL = 50;
var stick;

//Set the direction on the server and send the message what a button is clicked
function setDirection(direction, setter) {
  
  if(direction == "stop" && setter == "gamepad" && lastSetter != "gamepad") {
  
  } else if(direction == "stop" && setter == "keyboard" && lastSetter != "keyboard") {
  
  } else {
    console.log(direction + ' button clicked.');
  
    //Set on the server
    gapi.hangout.data.submitDelta({'direction': direction});  
    var robotsCombobox = document.getElementById('robotsCombobox');
    if(robotsCombobox.selectedIndex == 1){
      gapi.hangout.data.submitDelta({'robot1DirectionState': direction});
    }else if(robotsCombobox.selectedIndex == 2){
	  gapi.hangout.data.submitDelta({'robot2DirectionState': direction});
    }

    //Send the chat messages
    if(direction == "forward")
	  sendChatMessage('w');
    else if(direction == "backward")
      sendChatMessage('s');
    else if(direction == "left")
	  sendChatMessage('a');
    else if(direction == "right")
	  sendChatMessage('d');
    else if(direction == "stop")
	  sendChatMessage('p');

    //Ask to choose a robot before start trying to control them
    if(!robotEmail || robotEmail == "")
	  alert("Choose a robot first!");
	  
	lastSetter = setter;
  }
}

function doneButtonClicked() {
  changeVisibility('updateOptionsLayer',-1);
  
  var firstOptionTextbox = document.getElementById('firstOptionTextbox');
  var secondOptionTextbox = document.getElementById('secondOptionTextbox');
  var firstOptionNameTextbox = document.getElementById('firstOptionNameTextbox');
  var secondOptionNameTextbox = document.getElementById('secondOptionNameTextbox');
    
  if (firstOptionTextbox.value != null && firstOptionTextbox.value != "") {
    var username = firstOptionTextbox.value + "@gmail.com";
    //Sends the hangout url to the new user
    var hangoutUrl = gapi.hangout.getHangoutUrl();
    $.xmpp.sendMessage({to:username, body: hangoutUrl});
    //Sets the new user on the server
    gapi.hangout.data.submitDelta({'robot1Email': username});
	
    if (firstOptionNameTextbox.value != null && firstOptionNameTextbox.value != "")
	  gapi.hangout.data.submitDelta({'robot1Name': firstOptionNameTextbox.value});
	else
	  gapi.hangout.data.submitDelta({'robot1Name': username});
  }
  
  if (secondOptionTextbox.value != null && secondOptionTextbox.value != "") {
    var username = secondOptionTextbox.value + "@gmail.com";
    //Sends the hangout url to the new user
    var hangoutUrl = gapi.hangout.getHangoutUrl();
    $.xmpp.sendMessage({to:username, body: hangoutUrl});
    //Sets the new user on the server
    gapi.hangout.data.submitDelta({'robot2Email': username});
	
	if (secondOptionNameTextbox.value != null && secondOptionNameTextbox.value != "")
	  gapi.hangout.data.submitDelta({'robot2Name': secondOptionNameTextbox.value});
	else
	  gapi.hangout.data.submitDelta({'robot2Name': username});
  }
}

//Changes the visibility of a layer
function changeVisibility(layer, zIndex) {
  var updateLayer = document.getElementById(layer);
  updateLayer.style.zIndex = zIndex;
}

//Changes the source of a image
function changeImageSrc(imageId, imageSrc) {
  //Gets the image
  var imageElement = document.getElementById(imageId);
  //Sets with the new source
  imageElement.src = imageSrc;
}

//Add or update a option on the combobox
function updateOptionButtonClick() {
  changeVisibility('updateOptionsLayer',2);
}

//Send the chat message if it's different from the last one
function sendChatMessage(message){
  if(message != lastMessage){
    $.xmpp.sendMessage({to:robotEmail, body: message});
  }
  
  lastMessage = message;
}

//Sets the direction when a key is pressed
function keyPressed(e){
  var unicode=e.keyCode? e.keyCode : e.charCode;

  switch(unicode)
  {
    case 38: //Up arrow
      setDirection('forward','keyboard');
	  isForwardKeyDown = 1;
      break;
    case 40: //Down arrow
      setDirection('backward','keyboard');
      break;
    case 37: //Left arrow
      setDirection('left','keyboard');
      break;
    case 39: //Right arrow
      setDirection('right','keyboard');
      break;
    case 32: //Spacebar
      setDirection('stop','keyboard');
      break;
  }
}

//Sets the direction (stop) when a key is released
function keyReleased(e){
  var unicode=e.keyCode? e.keyCode : e.charCode;

  switch(unicode)
  {
    case 38: //Up arrow
      setDirection('stop','keyboard');
	  isForwardKeyDown = 0;
      break;
    case 40: //Down arrow
      setDirection('stop','keyboard');
      break;
    case 37: //Left arrow
	  if(isForwardKeyDown)
	    setDirection('forward','keyboard');
	  else
        setDirection('stop','keyboard');
      break;
    case 39: //Right arrow
      if(isForwardKeyDown)
	    setDirection('forward','keyboard');
	  else
        setDirection('stop','keyboard');
      break;
	case 85: //u
	  $.xmpp.sendMessage({to:robotEmail, body: "u"});
	  break;
	case 74: //j
	  $.xmpp.sendMessage({to:robotEmail, body: "j"});
	  break;
	case 70: //f
	  $.xmpp.sendMessage({to:robotEmail, body: "f"});
	  break;
  }
}

//Updates the UI
function updateStateUi(state) {
  var robotsCombobox = document.getElementById('robotsCombobox');
  //Updates the selected robot email
  robotEmail = robotsCombobox.options[robotsCombobox.selectedIndex].value;
  
  var directionState;
  if(robotsCombobox.selectedIndex == 1){
	directionState = state['robot1DirectionState'];
  }else if(robotsCombobox.selectedIndex == 2){
	directionState = state['robot2DirectionState'];
  }
  
  //Updates the combobox options
  robotsCombobox.options[1].innerHTML = state['robot1Name'];
  robotsCombobox.options[1].value = state['robot1Email'];
  robotsCombobox.options[2].innerHTML = state['robot2Name'];
  robotsCombobox.options[2].value = state['robot2Email'];
  
  //Updates the buttons images
  updateButtons(directionState.toString());
  
  //Calls the functions the a key is press or released
  document.onkeydown = keyPressed;
  document.onkeyup = keyReleased;
}

//Updates the buttons images
function updateButtons(direction) {
  //Gets the buttons
  var forwardButton = document.getElementById('forward');
  var backwardButton = document.getElementById('backward');
  var leftButton = document.getElementById('left');
  var rightButton = document.getElementById('right');
  var stopButton = document.getElementById('stop');
  
  //Sets all the buttons with the regular images
  forwardButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/forward.png';
  backwardButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/backward.png';
  leftButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/left.png';
  rightButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/right.png';		
  stopButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/stop.png';		
  
  //Sets the correspondent button with the selected version of the image
  if(direction == "forward")
	forwardButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/forwardSelected.png';
  else if(direction == "backward")
	backwardButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/backwardSelected.png';
  else if(direction == "left")
	leftButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/leftSelected.png';
  else if(direction == "right")
	rightButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/rightSelected.png';
  else if(direction == "stop")
	stopButton.src = 'http://magabot-control.googlecode.com/hg/static/pictures/stopSelected.png';
}

//Updated the selected robot email when the selected item of the combobox changes
function robotsComboboxChanged(){
  var robotsCombobox = document.getElementById('robotsCombobox');
  robotEmail = robotsCombobox.options[robotsCombobox.selectedIndex].value;
}

//Create and add a sprite to the page, then create the joystick wrapper, and finally start the draw loop.
function initGamepad() {
	stick = new Joystick();
	loopGamepad();
}

function loopGamepad() {
	var x = stick.getX();
	var y = stick.getY();
	if (y < 18672){
		setDirection('forward','gamepad');
	} else if (y > 46864) {
		setDirection('backward','gamepad');
	} else if (x < 18672) {
		setDirection('left','gamepad');
	} else if (x > 46864) {
		setDirection('right','gamepad');
	} else {
		setDirection('stop','gamepad');
	}
	
	setTimeout("loopGamepad()", INTERVAL);
}


// A function to be run at app initialization time which registers our callbacks
function init() {
  console.log('Init app.');

  var apiReady = function(eventObj) {
    if (eventObj.isApiReady) {
      console.log('API is ready');

      gapi.hangout.data.onStateChanged.add(function(eventObj) {
        updateStateUi(eventObj.state);
      });
      gapi.hangout.onParticipantsChanged.add(function(eventObj) {
        updateParticipantsUi(eventObj.participants);
      });

      updateStateUi(gapi.hangout.data.getState());
      updateParticipantsUi(gapi.hangout.getParticipants());

      gapi.hangout.onApiReady.remove(apiReady);
    }
  };

	//An example of bosh server. This site is working but it can change or go down.
	//If you are going to have a production site, you must install your own BOSH server
	var url ="http://bosh.metajack.im:5280/xmpp-httpbind";
	var contactList = $("#contacts");
	$.xmpp.connect({url:url, jid: jid, password: password,
		onConnect: function(){
			$.xmpp.setPresence(null);
		},
		onPresence: function(presence){
			var contact = $("<li>");
			contact.append("<a href='javascript:void(0)'>"+ presence.from +"</a>");
			contact.find("a").click(function(){
					var id = MD5.hexdigest(presence.from);
					var conversation = $("#"+id);
					if(conversation.length == 0)
						openChat({to:presence.from});
			});
			contactList.append(contact);
		}
    });
	
  // This application is pretty simple, but use this special api ready state
  // event if you would like to any more complex app setup.
  gapi.hangout.onApiReady.add(apiReady);
}

gadgets.util.registerOnLoadHandler(init);
